package com.mobilepay.moneypig.model.activity.home;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.share.sdk.openapi.algorithm.MD5;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.githang.statusbar.StatusBarCompat;
import com.mobilepay.moneypig.R;
import com.mobilepay.moneypig.alipay.AlipayActivity;
import com.mobilepay.moneypig.base.BaseActivity;
import com.mobilepay.moneypig.base.NoDoubleClickListener;
import com.mobilepay.moneypig.config.Constant;
import com.mobilepay.moneypig.config.NetConfig;
import com.mobilepay.moneypig.model.application.App;
import com.mobilepay.moneypig.model.dialog.PayTypeDialog;
import com.mobilepay.moneypig.okhttp.HttpUtils;
import com.mobilepay.moneypig.response.ResponseResult;
import com.mobilepay.moneypig.response.pay.AliPayData;
import com.mobilepay.moneypig.response.pay.WxPayResponse;
import com.mobilepay.moneypig.utils.CommonUtil;
import com.mobilepay.moneypig.utils.GsonUtil;
import com.mobilepay.moneypig.utils.IsSoftShow;
import com.mobilepay.moneypig.utils.LogDebug;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.utils.Log;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.util.InetAddressUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * Created by xlm on 2017/7/31 0031
 */

public class UpVipActivity extends BaseActivity {
    private static final String TAG = "UpVipActivity";
    private RelativeLayout mRelativeBack;
//    private Button mButtonUp;
//    private EditText mEditMobile;
//    private EditText mEditAddress;
    private String bgUrl;
//    private ImageView mImagCover;
    private RecyclerView mUpVipRecycle;

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_upgrade);
    }

    @Override
    protected void initViews() {
        mUpVipRecycle = (RecyclerView) findViewById(R.id.up_recycle);
        mRelativeBack = (RelativeLayout) findViewById(R.id.upgrade_back);
//        mButtonUp = (Button) findViewById(R.id.upgrade_button);
//        mEditMobile = (EditText) findViewById(R.id.upgrade_mobile);
//        mEditAddress = (EditText) findViewById(R.id.upgrade_address);
//        mImagCover = (ImageView) findViewById(R.id.upgrade_cover);
    }

    @Override
    protected void onGetIntent(Intent intent) {
        bgUrl = getIntent().getStringExtra("background");
    }

    private IWXAPI WXApi;

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
//        if (!CommonUtil.isEmpty(bgUrl)) {
//            Glide.with(getThis())
//                    .load(bgUrl)
//                    .into(mImagCover);
//        }
//        WXApi = WXAPIFactory.createWXAPI(getThis(), Constant.WEIXIN_PAY);
//        WXApi.registerApp(Constant.WEIXIN_PAY);
        //判断软键盘是否显示
//        IsSoftShow.doMonitorSoftKeyWord(findViewById(R.id.root), new IsSoftShow.OnSoftKeyWordShowListener() {
//            @Override
//            public void hasShow(boolean isShow) {
//                if (isShow) {
//                    StatusBarCompat.setStatusBarColor(UpVipActivity.this, Color.parseColor("#40000000"));
//                } else {
//                    StatusBarCompat.setStatusBarColor(UpVipActivity.this, Color.parseColor("#e46641"));
//                }
//            }
//        });

        UpVipAdapter upVipAdapter = new UpVipAdapter(UpVipActivity.this);
        upVipAdapter.setUpvipData(bgUrl);
        mUpVipRecycle.setLayoutManager(new LinearLayoutManager(UpVipActivity.this, LinearLayoutManager.VERTICAL, false));
        mUpVipRecycle.setAdapter(upVipAdapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //移除软键盘监听
//        IsSoftShow.doMonitorSoftKeyWord(findViewById(R.id.root), null);
    }

    @Override
    protected void onSetListener() {
        mRelativeBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void commitData(String mobile, String address) {
        String uid = String.valueOf(App.getApp().getUserInfo().getData().getUid());
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.upVip);
        param.add("uid", uid);
        param.add("address", mobile + address);
        param.add("sign", param.getMd5String());
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                if (CommonUtil.isForeground(getThis())) {
                    showToastShort(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                //订单信息返回后，调用支付宝支付
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 1) {
                        final AliPayData data = GsonUtil.GsonToBean(string, AliPayData.class);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showPayTypeDialog(data);
                            }
                        });
                    } else {
                        showToastShort(responseResult.getInfo());
                    }
                }
            }
        });
    }

    private PayTypeDialog payTypeDialog;

    private void showPayTypeDialog(final AliPayData payData) {
        if (payTypeDialog == null) {
            payTypeDialog = new PayTypeDialog(this);
        }
        payTypeDialog.setCancelable(true);
        payTypeDialog.setListener(new PayTypeDialog.Listener() {
            @Override
            public void onSelectedAli() {
                startPayCode(payData.getData().getTotal_amount(), payData.getData().getRqcode_url(), "alipay");
            }

            @Override
            public void onSelectedWeixin() {
                startPayCode(payData.getData().getTotal_amount(), payData.getData().getRqcode_url(), "weixin");
            }
        });
        payTypeDialog.show();
    }

    private void startPayCode(String amount, String code_url, String type) {
        Intent intent = new Intent();
        intent.setClass(UpVipActivity.this, PayCodeActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("amount", amount);
        intent.putExtra("code_url", code_url);
        startActivity(intent, false);
    }

    private static class UpVipAdapter extends RecyclerView.Adapter<UpVipHolder> {
        private Context mContext;
        private String mStringUrl;

        public UpVipAdapter(Context context) {
            mContext = context;
        }

        private void setUpvipData(String stringUrl) {
            this.mStringUrl = stringUrl;
        }

        @Override
        public UpVipHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new UpVipHolder(LayoutInflater.from(mContext).inflate(R.layout.upvip_item, parent, false));
        }

        @Override
        public void onBindViewHolder(final UpVipHolder holder, int position) {
            if (!CommonUtil.isEmpty(mStringUrl)) {
                Glide.with(mContext).load(mStringUrl).asBitmap().centerCrop()
                        .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                        .into(holder.mImageViewCover);
            }

            holder.mButtonCommit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (CommonUtil.isEmpty(holder.mEditTextPhone.getText().toString())) {
                        ((UpVipActivity) mContext).showToastShort("手机号不能为空");
                        return;
                    }
                    if (CommonUtil.isEmpty(holder.mEditTextAddress.getText().toString())) {
                        ((UpVipActivity) mContext).showToastShort("收货地址不能为空");
                        return;
                    }
                    ((UpVipActivity) mContext).commitData(holder.mEditTextPhone.getText().toString(),
                            holder.mEditTextAddress.getText().toString());
                }
            });
        }

        @Override
        public int getItemCount() {
            return 1;
        }
    }

    static class UpVipHolder extends RecyclerView.ViewHolder {
        ImageView mImageViewCover;
        TextView mTextViewTitle;
        EditText mEditTextPhone;
        EditText mEditTextAddress;
        Button mButtonCommit;

        public UpVipHolder(View itemView) {
            super(itemView);
            mImageViewCover = (ImageView) itemView.findViewById(R.id.upgrade_cover);
            mTextViewTitle = (TextView) itemView.findViewById(R.id.update_title);
            mEditTextPhone = (EditText) itemView.findViewById(R.id.upgrade_mobile);
            mEditTextAddress = (EditText) itemView.findViewById(R.id.upgrade_address);
            mButtonCommit = (Button) itemView.findViewById(R.id.upgrade_button);
        }
    }


    //////////////////////////////////////////----------微信本地参数生成和调用微信支付------------------------/////////////////////
    private void getWeiXData(String out_trade_no) {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("out_trade_no", out_trade_no);
        HttpUtils.getInstance().params(param).executeWeiXPost(new HttpUtils.HttpListener() {
            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 1) {
                        WxPayResponse response = GsonUtil.GsonToBean(string, WxPayResponse.class);
                        PayReq req = new PayReq();
                        req.appId = response.getData().getAppid();
                        req.partnerId = response.getData().getPartnerid();
                        req.prepayId = response.getData().getPrepayid();
                        req.nonceStr = response.getData().getNoncestr();
                        req.timeStamp = String.valueOf(response.getData().getTimestamp());
                        req.packageValue = response.getData().getPackageX();
                        req.sign = response.getData().getSign();
                        WXApi.sendReq(req);
//                        new GetPrepayIdTask().execute();
                    } else {
                        showToastShort(responseResult.getInfo());
                    }
                }
            }
        });
    }

    private static String urlorder = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    private static String appid = "wxde4ec2de04586188";
    private static String mch_id = "1487756572";
    private static String api_key = "b91d781d575e8b43dbd86c2b3636ae06";

    //生成签名
    public static String genPackageSign(List<NameValuePair> params) {
        try {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < params.size(); i++) {
                sb.append(params.get(i).getName());
                sb.append('=');
                sb.append(params.get(i).getValue());
                sb.append('&');
            }
            sb.append("key=");
            sb.append(api_key);
            return MD5.getMessageDigest(sb.toString().getBytes("utf-8")).toUpperCase();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    //微信支付调用统一下单接口，随机字符串
    public static String genNonceStr() {
        try {
            Random random = new Random();
            return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    //微信out_trade_no
    public static String genTradeNum() {
        try {
            Random random = new Random();
            return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)
                    + System.currentTimeMillis()).getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    //生成 XML
    public static String toXml(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (int i = 0; i < params.size(); i++) {
            sb.append("<").append(params.get(i).getName()).append(">");
            sb.append(params.get(i).getValue());
            sb.append("</").append(params.get(i).getName()).append(">");
        }
        sb.append("</xml>");
        LogDebug.i(TAG, sb.toString());
        return sb.toString();
    }

    /**
     * 得到本机IP地址，WIFI下获取的是局域网IP，数据流量下获取的是公网IP
     *
     * @return
     */
    public static String getIPAddress() {
        try {
            Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
            // 遍历所用的网络接口
            while (en.hasMoreElements()) {
                NetworkInterface nif = en.nextElement();// 得到每一个网络接口绑定的所有ip
                Enumeration<InetAddress> inet = nif.getInetAddresses();
                // 遍历每一个接口绑定的所有ip
                while (inet.hasMoreElements()) {
                    InetAddress ip = inet.nextElement();
                    if (!ip.isLoopbackAddress()
                            && InetAddressUtils.isIPv4Address(ip
                            .getHostAddress())) {
                        return ip.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            Log.e(TAG, "获取本地ip地址失败", e);
        }
        return null;
    }


    public String genEntity() {
        String nonceStr = genNonceStr();
        List<NameValuePair> packageParams = new ArrayList<NameValuePair>();
        // APPID
        packageParams.add(new BasicNameValuePair("appid", appid));
        // 商品描述
        packageParams.add(new BasicNameValuePair("body", "duolaibei"));
        // 商户ID
        packageParams.add(new BasicNameValuePair("mch_id", mch_id));
        // 随机字符串
        packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
        // 回调接口地址
        packageParams.add(new BasicNameValuePair("notify_url", "http://www.hiima.cn/index/plugin/execute/_plugin/Payment/_controller/Alipay/_action/notify.html"));
        // 我们的订单号
        packageParams.add(new BasicNameValuePair("out_trade_no", genTradeNum()));
        // 提交用户端ip
        packageParams.add(new BasicNameValuePair("spbill_create_ip", getIPAddress()));

        BigDecimal totalFeeBig = new BigDecimal("10");
        int totalFee = totalFeeBig.multiply(new BigDecimal(100)).intValue();
        // 总金额，单位为 分 !
        packageParams.add(new BasicNameValuePair("total_fee", String.valueOf(totalFee)));
        // 支付类型， APP
        packageParams.add(new BasicNameValuePair("trade_type", "APP"));
        // 生成签名
        String sign = genPackageSign(packageParams);
        packageParams.add(new BasicNameValuePair("sign", sign));
        String xmlstring = toXml(packageParams);
        try {
            //避免商品描述中文字符编码格式造成支付失败
            return new String(xmlstring.getBytes(), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static class SSLSocketFactoryEx extends SSLSocketFactory {
        SSLContext sslContext = SSLContext.getInstance("TLS");

        SSLSocketFactoryEx(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
                KeyStoreException, UnrecoverableKeyException {
            super(truststore);
            TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws java.security.cert.CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws java.security.cert.CertificateException {
                }
            };

            sslContext.init(null, new TrustManager[]{tm}, null);
        }


        @Override
        public Socket createSocket(Socket socket, String host, int port,
                                   boolean autoClose) throws IOException, UnknownHostException {
            return sslContext.getSocketFactory().createSocket(socket, host,
                    port, autoClose);
        }

        @Override
        public Socket createSocket() throws IOException {
            return sslContext.getSocketFactory().createSocket();
        }
    }


    private static HttpClient getNewHttpClient() {
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            registry.register(new Scheme("https", sf, 443));
            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
            return new DefaultHttpClient(ccm, params);
        } catch (Exception e) {
            return new DefaultHttpClient();
        }
    }


    public static byte[] httpPost(String url, String entity) {
        if (url == null || url.length() == 0) {
            Log.e(TAG, "httpPost, url is null");
            return null;
        }
        HttpClient httpClient = getNewHttpClient();
        HttpPost httpPost = new HttpPost(url);
        try {
            httpPost.setEntity(new StringEntity(entity));
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            HttpResponse resp = httpClient.execute(httpPost);
            if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                Log.e(TAG, "httpGet fail, status code = " + resp.getStatusLine().getStatusCode());
                return null;
            }
            return EntityUtils.toByteArray(resp.getEntity());
        } catch (Exception e) {
            Log.e(TAG, "httpPost exception, e = " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取子结点的xml
     *
     * @param children
     * @return String
     */
    public static String getChildrenText(List children) {
        StringBuilder sb = new StringBuilder();
        if (!children.isEmpty()) {
            for (Object aChildren : children) {
                Element e = (Element) aChildren;
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<").append(name).append(">");
                if (!list.isEmpty()) {
                    sb.append(getChildrenText(list));
                }
                sb.append(value);
                sb.append("</").append(name).append(">");
            }
        }
        return sb.toString();
    }


    public static Map doXMLParse(String strxml) throws Exception {
        if (null == strxml || "".equals(strxml)) {
            return null;
        }
        Map m = new HashMap();
        InputStream in = new ByteArrayInputStream(strxml.getBytes());
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        for (Object aList : list) {
            Element e = (Element) aList;
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if (children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = getChildrenText(children);
            }
            m.put(k, v);
        }
        // 关闭流
        in.close();
        return m;
    }

    /**
     * 发送支付请求
     *
     * @param prepayId 预付Id
     */
    private void sendPayReq(String prepayId) {
        PayReq req = new PayReq();
        req.appId = appid;
        req.partnerId = mch_id;
        req.prepayId = prepayId;
        req.nonceStr = genNonceStr();
        req.timeStamp = String.valueOf(System.currentTimeMillis());
        req.packageValue = "Sign=WXPay";
        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
        req.sign = genPackageSign(signParams);
        WXApi.sendReq(req);
    }


    /**
     * 异步网络请求获取预付Id
     */
    private class GetPrepayIdTask extends AsyncTask<String, Void, String> {
        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onPostExecute(String prepay_id) {
            // 第三步, 发送支付请求
            sendPayReq(prepay_id);
        }

        @Override
        protected String doInBackground(String... params) {
            // 网络请求获取预付Id
            String url = urlorder;
            String entity = genEntity();
            byte[] buf = httpPost(url, entity);
            if (buf != null && buf.length > 0) {
                try {
                    Map map = doXMLParse(new String(buf));
                    LogDebug.i(TAG, new String(buf));
                    return (String) map.get("prepay_id");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    }
}
